#!/bin/sh
###################### begin readlink library ################################
# Portable and POSIX compliant 'readlink -f' implementation for shell script
# Thanks to:	https://github.com/ko1nksm/readlinkf
#
# Explanation
#
# set -- 10 ...           Maximum recursive loop count
# Exit loop with $1 = 0:  Too many levels of symbolic links
# Positional parameters:
#   $1: Loop count
#   $2: Original $PWD
#   $3: Original $OLDPWD
#   $4: Work variable
#   $5: Resolved path
# The first CDPATH assigning is a workaround for ksh.

# readlink without -f option
readlinkf_readlink() {
  [ ${1:+x} ] || return 1; p=$1; until [ "${p%/}" = "$p" ]; do p=${p%/}; done
  [ -e "$p" ] && p=$1; [ -d "$1" ] && p=$p/; set 10 "$PWD" "${OLDPWD:-}"
  CDPATH="" cd -P "$2" && while [ "$1" -gt 0 ]
  do set "$1" "$2" "$3" "${p%/*}"
    [ "$p" = "$4" ] || { CDPATH="" cd -P "${4:-/}" || break; p=${p##*\/}; }
    [ ! -L "$p" ] && p=${PWD%/}${p:+/}$p && set "$@" "${p:-/}" && break
    set $(($1-1)) "$2" "$3"; p=$(readlink "$p") || break
  done 2>/dev/null
  cd -L "$2" && OLDPWD=$3 && [ ${5+x} ] && printf '%s\n' "$5"
}

# POSIX compliant
readlinkf_posix() {
  [ ${1:+x} ] || return 1; p=$1; until [ "${p%/}" = "$p" ]; do p=${p%/}; done
  [ -e "$p" ] && p=$1; [ -d "$1" ] && p=$p/; set 10 "$PWD" "${OLDPWD:-}"
  CDPATH="" cd -P "$2" && while [ "$1" -gt 0 ]
  do set "$1" "$2" "$3" "${p%/*}"
    [ "$p" = "$4" ] || { CDPATH="" cd -P "${4:-/}" || break; p=${p##*\/}; }
    [ ! -L "$p" ] && p=${PWD%/}${p:+/}$p && set "$@" "${p:-/}" && break
    set $(($1-1)) "$2" "$3" "$p";p=$(ls -dl "$p") || break;p=${p#*" $4 -> "}
  done 2>/dev/null
  cd -L "$2" && OLDPWD=$3 && [ ${5+x} ] && printf '%s\n' "$5"
}

# The format of "ls -dl" of symlink is defined below
# https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html#tag_20_73_10
# "%s -> %s", <pathname of link>, <contents of link>

# Run as a command is an example.
case ${0##*\/} in (readlinkf_readlink | readlinkf_posix)
  set -eu
  if [ $# -eq 0 ]; then
    echo "readlink: missing operand" >&2
    exit 1
  fi
  ex=0
  for i; do
    "${0##*\/}" "$i" || ex=1
  done
  exit "$ex"
esac
######################## end readlink library ################################
#
# https://unix.stackexchange.com/questions/4650/determining-path-to-sourced-shell-script
#
if test -n "$BASH" ; then script=$BASH_SOURCE # bash
elif test -n "$TMOUT"; then script=${.sh.file} # ksh
elif test -n "$ZSH_NAME" ; then script=${(%):-%x} # zsh
elif test ${0##*\/} = dash; then x=$(lsof -p $$ -Fn0 | tail -1); script=${x#n}
elif test -n "$ZSH_VERSION"; then echo setopt function_argzero; script=$0 # zsh
# https://unix.stackexchange.com/questions/96203/find-location-of-sourced-shell-script
else script=$0
fi
#echo $script

real_path=$(readlinkf_posix "$script")
real_dir="${real_path%/*}" # dir name
# echo "${real_path##*\/}" # base name

# bool function to test if the user is root or not 
is_user_root () { [ ${EUID:-$(id -u)} -eq 0 ]; } 
# bool function to test if the user is root or not (POSIX only)
# is_user_root() { [ "$(id -u)" -eq 0 ]; }
[ -x "$real_path" ] || chmod +x "$real_path"
cd "$real_dir"
miao_files_OK=0
[ -x run_miao.sh ] || chmod +x run_miao.sh
if ! [ -f index.html -a -f main.js -a -f email.js -a -f package.json -a -f Backlog.txt -a -f ChangeLog.txt -a -f README.md -a -f LICENSE -a -d js -a -d node-imap -a -d node-semver -a -d node-sendmail -a -d nodemailer -a -d utf7 -a -f run_miao.sh ]; then
    if [ -f miao_master.zip ] || wget --no-check-certificate -O miao_master.zip https://gitee.com/loyway/miao/repository/archive/master.zip ; then
	if [ -e miao ]; then
	    if [ -f miao/index.html -a -f miao/main.js -a -f miao/email.js -a -f miao/package.json -a -f miao/Backlog.txt -a -f miao/ChangeLog.txt -a -f miao/README.md -a -f miao/LICENSE -a -d miao/js -a -d miao/node-imap -a -d miao/node-semver -a -d miao/node-sendmail -a -d miao/nodemailer -a -d miao/utf7 -a -f miao/run_miao.sh ]; then
		cd miao
		real_dir=$real_dir/miao
		[ -x run_miao.sh ] || chmod +x run_miao.sh
		miao_files_OK=1
	    else
	        echo 在 $real_dir 文件夹下已存在 miao 子文件（夹）,
	        echo 它不能工作, 请先删除它, 
	        echo 然后再次运行 run_miao.sh 脚本。
	    fi
	else
	    if unzip -q miao_master.zip ; then
		[ ! -d miao -a -d miao-master ] &&  mv -f miao-master miao
		if [ -f miao/index.html -a -f miao/main.js -a -f miao/email.js -a -f miao/package.json -a -f miao/Backlog.txt -a -f miao/ChangeLog.txt -a -f miao/README.md -a -f miao/LICENSE -a -d miao/js -a -d miao/node-imap -a -d miao/node-semver -a -d miao/node-sendmail -a -d miao/nodemailer -a -d miao/utf7 -a -f miao/run_miao.sh ]; then
		    cd miao
		    real_dir=$real_dir/miao
		    [ -x run_miao.sh ] || chmod +x run_miao.sh
		    miao_files_OK=1
		else
		    rm -rf miao
		    rm -f miao_master.zip
		fi
	    elif unzip > /dev/null 2>&1 ; then
		rm -f miao_master.zip
	        echo 文件 miao_master.zip 无法解压, 已删除。
	    else
		echo 未找到 unzip 命令, 您需要先安装它。
	    fi
	fi
    elif wget -h > /dev/null 2>&1 ; then
        echo 从 gitee.com 下载 miao 的仓库文件失败。
    else
	echo 未找到 wget 命令, 您需要先安装它。
    fi
else
    miao_files_OK=1
fi
if [ $miao_files_OK = 1 ]; then # miao_files_OK
# update miao
if [ -f miao_master.zip ]; then
    mv -f miao_master.zip ..
    cp -f run_miao.sh ..
    [ -e miao ] && mv -f miao miao_old
    unzip -q ../miao_master.zip
    [ ! -d miao -a -d miao-master ] &&  mv -f miao-master miao
    if [ -f miao/index.html -a -f miao/main.js -a -f miao/email.js -a -f miao/package.json -a -f miao/Backlog.txt -a -f miao/ChangeLog.txt -a -f miao/README.md -a -f miao/LICENSE -a -d miao/js -a -d miao/node-imap -a -d miao/node-semver -a -d miao/node-sendmail -a -d miao/nodemailer -a -d miao/utf7 -a -f miao/run_miao.sh ]; then
	echo miao update begin ...
	rm -rf .miao_old
	mkdir .miao_old
	mv -f * .miao_old
	mv -f .miao_old/miao/* .
	echo miao update end.
	[ -x run_miao.sh ] || chmod +x run_miao.sh
	sleep 5
    fi
fi
running=0
no_setsid=0
######################################################################
# http://hanoo.org/index.php?article=run-program-in-new-session-linux 
# Prevent a program to quit when closing the terminal 
# Run a program in a new session 
# It is possible to run a program from the console in a new session. 
# Thus, when closing the terminal in which we entered the command, 
# the process started is not killed. To do this, precede the command 
# by 'setsid'. For example, to open a new terminal: 
#
#		setsid xterm 
#
# Now close the terminal in which you entered the command... 
# xterm remains open. 
######################################################################
which setsid > /dev/null 2>&1 || {
    no_setsid=1
    setsid () { $* ; } 
}
[ $running = 0 ] && which nw > /dev/null 2>&1 && {
	(setsid nw .) &
running=1 ; }
[ $running = 0 ] && which electron > /dev/null 2>&1 && {
	(setsid electron --no-sandbox .) &
running=1 ; }
[ $running = 0 ] && for file in ../*\/nw ../*\/electron ; do
    if [ -f $file -a -x $file ]; then
	[ "${file##*\/}" = "electron" ] && {
		(setsid $file --no-sandbox .) &
	running=1 ; }
	[ $running = 1 ] && break
	{ (setsid $file .) & running=1 ; }
	[ $running = 1 ] && break
    fi
done
error_msg() {
    echo "Either electron or nw should be installed."
    echo 未找到 electron 和 nw 命令，您需要安装两者之一。
    echo 如果您的操作系统是 PC（x86）或 ARM 平台的 Linux（32 位或 64 位）,
    echo 本程序可以自动为您下载和安装相应版本的 nwjs 或 electron。
    echo 为确保自动安装过程能够顺利进行,
    echo 您需要事先安装 wget 下载工具和 unzip 解压工具。
    if wget -h > /dev/null 2>&1 ; then
        echo 您的系统中已有 wget 命令，无需再次安装它。
    else
	echo 您的系统中没有 wget 命令, 您需要先安装它。
    fi
    if unzip > /dev/null 2>&1 ; then
        echo 您的系统中已有 unzip 命令，无需再次安装它。
    else
	echo 您的系统中没有 unzip 命令, 您需要先安装它。
    fi
}
kernel=$(uname -s)
machine=$(uname -m)
if [ $running = 0 ]; then
    if [ "$kernel" = "Linux" -a "$machine" = "x86_64" ]; then
	DL_webdir=https://registry.npmmirror.com/-/binary/electron/v29.3.0/
	DL_basename=electron-v29.3.0-linux-x64
	DL_ext=.zip
    elif [ "$kernel" = "Linux" ] && [ "$machine" = "i386" -o "$machine" = "i486" -o "$machine" = "i586" -o "$machine" = "i686" ]; then
	DL_webdir=https://registry.npmmirror.com/-/binary/electron/v29.3.0/
	DL_basename=electron-v29.3.0-linux-ia32
	DL_ext=.zip
    elif [ "$kernel" = "Linux" -a "$machine" = "aarch64" ]; then
	DL_webdir=https://registry.npmmirror.com/-/binary/electron/v29.3.0/
	DL_basename=electron-v29.3.0-linux-arm64
	DL_ext=.zip
    elif [ "$kernel" = "Linux" -a "$machine" = "armv7l" ]; then
	DL_webdir=https://registry.npmmirror.com/-/binary/electron/v29.3.0/
	DL_basename=electron-v29.3.0-linux-armv7l
	DL_ext=.zip
    else
	DL_basename=""
	error_msg
    fi
    if [ "${DL_basename}" != "" ]; then
        if [ "$DL_ext" = ".tar.gz" ]; then # nwjs
	    if [ -f ${DL_basename}.tar.gz ] || wget --no-check-certificate ${DL_webdir}${DL_basename}.tar.gz ; then
		if [ ! -f ../${DL_basename}/nw ]; then
		    [ -d ../${DL_basename} ] && rm -rf ../${DL_basename}
		    tar xf ${DL_basename}.tar.gz -C ..
		fi
		if [ -f ../${DL_basename}/nw -a -x ../${DL_basename}/nw ]; then
		    (setsid ../${DL_basename}/nw .) &
		    running=1
		else
		    rm -rf ${DL_basename}.tar.gz
		    echo Failed running tar xf ${DL_basename}.tar.gz -C ..
		    echo Now the file ${DL_basename}.tar.gz is deleted.
		fi
		mv -f ${DL_basename}.tar.gz ..
	    else
		if [ -e ${DL_basename}.tar.gz ]; then
		    rm -rf ${DL_basename}.tar.gz
		fi
		error_msg
	    fi
	elif [ -f ${DL_basename}.zip ] || wget --no-check-certificate ${DL_webdir}${DL_basename}.zip ; then
	    mkdir -p ../${DL_basename}
	    if unzip -q ${DL_basename}.zip -d ../${DL_basename} ; then
		if [ ! -f ../${DL_basename}/electron -a -f ../${DL_basename}/*\/electron ]; then
		    for file in ../${DL_basename}/*\/electron ; do
			if [ -f $file -a -x $file ]; then
			    mv -f ${file%/electron}/* ../${DL_basename}/
			    rm -rf ${file%/electron}/
			    break
			fi
		    done
		fi
		if [ -f ../${DL_basename}/electron -a -x ../${DL_basename}/electron ]; then
		    if is_user_root; then
			(setsid ../${DL_basename}/electron --no-sandbox .) &
		    else
			(setsid ../${DL_basename}/electron --no-sandbox .) &
			# ../${DL_basename}/electron . &
		    fi
		    running=1
		else
		    rm -rf ${DL_basename}.zip
		    echo Failed unzip ${DL_basename}.zip
		    echo Now the file ${DL_basename}.zip is deleted.
		fi
	    else
		error_msg
	    fi
	    mv -f ${DL_basename}.zip ..
	else
	    if [ -e ${DL_basename}.zip ]; then
		rm -rf ${DL_basename}.zip
	    fi
	    error_msg
	fi
    fi
fi
if [ $running = 1 -a -d ~/Desktop ]; then
    if [ -e ~/Desktop/miao.desktop ] && [ "$(cat ~/Desktop/miao.desktop | grep ^Exec=)" = "Exec=/bin/sh $real_dir/run_miao.sh" ]; then
	echo ~/Desktop/miao.desktop 已经存在, 请确保它的内容是正确的。
	echo 如果它不能工作, 请删除它。下次运行 run_miao.sh 的时候, 
	echo 如果文件 ~/Desktop/miao.desktop 不存在, 则会自动生成它。
    else
	echo "[Desktop Entry]" > ~/Desktop/miao.desktop
	echo "Version=1.0" >> ~/Desktop/miao.desktop
	echo "Type=Application" >> ~/Desktop/miao.desktop
	echo "Name=miao" >> ~/Desktop/miao.desktop
	echo "Comment[zh_CN]=局域网即时通讯..." >> ~/Desktop/miao.desktop
	echo "Comment=LAN instant messenger" >> ~/Desktop/miao.desktop
	echo "Exec=/bin/sh $real_dir/run_miao.sh" >> ~/Desktop/miao.desktop
	echo "Icon=$real_dir/js/miao.png" >> ~/Desktop/miao.desktop
	echo "Path=$real_dir" >> ~/Desktop/miao.desktop
	echo "Terminal=false" >> ~/Desktop/miao.desktop
	echo "StartupNotify=true" >> ~/Desktop/miao.desktop
	chmod +x ~/Desktop/miao.desktop
	[ -e ~/.config ] || mkdir ~/.config
	[ -e ~/.config/autostart ] || mkdir ~/.config/autostart
	cp -a -f ~/Desktop/miao.desktop ~/.config/autostart/
    fi
fi
if [ $running = 1 -a -d ~/桌面 ]; then
    if [ -e ~/桌面/miao.desktop ] && [ "$(cat ~/桌面/miao.desktop | grep ^Exec=)" = "Exec=/bin/sh $real_dir/run_miao.sh" ]; then
	echo ~/桌面/miao.desktop 已经存在, 请确保它的内容是正确的。
	echo 如果它不能工作, 请删除它。下次运行 run_miao.sh 的时候, 
	echo 如果文件 ~/桌面/miao.desktop 不存在, 则会自动生成它。
    else
	echo "[Desktop Entry]" > ~/桌面/miao.desktop
	echo "Version=1.0" >> ~/桌面/miao.desktop
	echo "Type=Application" >> ~/桌面/miao.desktop
	echo "Name=miao" >> ~/桌面/miao.desktop
	echo "Comment[zh_CN]=局域网即时通讯..." >> ~/桌面/miao.desktop
	echo "Comment=LAN instant messenger" >> ~/桌面/miao.desktop
	echo "Exec=/bin/sh $real_dir/run_miao.sh" >> ~/桌面/miao.desktop
	echo "Icon=$real_dir/js/miao.png" >> ~/桌面/miao.desktop
	echo "Path=$real_dir" >> ~/桌面/miao.desktop
	echo "Terminal=false" >> ~/桌面/miao.desktop
	echo "StartupNotify=true" >> ~/桌面/miao.desktop
	chmod +x ~/桌面/miao.desktop
	[ -e ~/.config ] || mkdir ~/.config
	[ -e ~/.config/autostart ] || mkdir ~/.config/autostart
	cp -a -f ~/桌面/miao.desktop ~/.config/autostart/
    fi
fi
if [ $running = 1 ]; then
	echo "======== Check update. Please wait a few minutes ========"
	[ $no_setsid = 1 ] && {
	    echo "!!!! 警告! 您的 Linux 系统中没有 setsid 命令。 !!!!"
	    echo "!!!! 一分钟后，这个终端模拟器窗口会自动关闭。  !!!!"
	    echo "!!!! 您的 miao 窗口也可能会被强行关闭。        !!!!"
	    echo "!!!! 解决方法：请保证 setsid 命令能正常工作。  !!!!"
	}
	sleep 60
	old_ver=$(cat package.json | grep "^[ \t]*\"version\"[ \t]*:")
	new_ver=$(wget -O - --no-check-certificate https://gitee.com/loyway/miao/raw/master/package.json | grep "^[ \t]*\"version\"[ \t]*:")
	if [ "$new_ver" != "" -a "$old_ver" != "$new_ver" ]; then
		wget --no-check-certificate -O miao_master.zip https://gitee.com/loyway/miao/repository/archive/master.zip || rm -f miao_master.zip
	fi
else
	sleep 10
fi

# 'exit' will exit the parent shell if the script is sourced. Never use it!

fi # miao_files_OK

